/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package cz.muni.fi.pb138;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author lucka
 */
class AuthTest {
    private static final String MAXID = "//user[not(@id <= preceding-sibling::user/@id) and not(@id <=following-sibling::user/@id)]/@id";
    private File file;
    private Document doc;
    private XPath xpath;
  

    public AuthTest() throws SAXException, ParserConfigurationException,
            IOException {
        file = new File(BiographyServlet.PROJECT_PATH + "/web/WEB-INF/users.xml");
        URI uri = file.toURI();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(uri.toString());
        xpath = XPathFactory.newInstance().newXPath();
    }
    
    public void printUsers() {
        NodeList divList = doc.getElementsByTagName("user");
        for (int i = 0; i < divList.getLength(); i++) 
            if (divList.item(i) instanceof Element) {
                Element divElement = (Element) divList.item(i);
                String atr= divElement.getAttribute("name");
                System.out.println(atr);
            }
    }
    
    public boolean authenticate(String name, String password) {
        NodeList divList = doc.getElementsByTagName("user");
        for (int i = 0; i < divList.getLength(); i++) 
            if (divList.item(i) instanceof Element) {
                Element divElement = (Element) divList.item(i);
                String usrName = divElement.getAttribute("name");
                String usrPass = divElement.getAttribute("password");
                if (usrName.equals(name) && usrPass.equals(password)){
                    return true;
                }
            }
        return false;
    }
    
    public boolean hasSameName(String name) {
        NodeList divList = doc.getElementsByTagName("user");
        for (int i = 0; i < divList.getLength(); i++) 
            if (divList.item(i) instanceof Element) {
                Element divElement = (Element) divList.item(i);
                String usrName = divElement.getAttribute("name");
                if (usrName.equals(name)){
                    return true;
                }
            }
        return false;
    }
    
    public Integer getUserID(String name) {
        NodeList divList = doc.getElementsByTagName("user");
        for (int i = 0; i < divList.getLength(); i++) 
            if (divList.item(i) instanceof Element) {
                Element divElement = (Element) divList.item(i);
                String usrName = divElement.getAttribute("name");
                if (usrName.equals(name)){
                    return Integer.parseInt(divElement.getAttribute("id"));
                }
            }
        return null;
    }
    
    
    
    
            
    public void addUser(String name, String password) throws IOException, TransformerException, XPathExpressionException {
        Element root = doc.getDocumentElement();
        Element newUser = doc.createElement("user");
        int id = maxID();
        id = id+1;
        newUser.setAttribute("id", new Integer(id).toString());
        newUser.setAttribute("name", name);
        newUser.setAttribute("password", password);
        root.appendChild(newUser);
        serializetoXML(file.toURI());
    }
    
    public int maxID() throws XPathExpressionException {
        Double id = (Double)xpath.evaluate(MAXID, doc, XPathConstants.NUMBER);
        return id.intValue();
    }
    
    public void serializetoXML(URI output)
            throws IOException, TransformerConfigurationException, TransformerException {
        // Vytvorime instanci tovarni tridy
        TransformerFactory factory = TransformerFactory.newInstance();
        // Pomoci tovarni tridy ziskame instanci tzv. kopirovaciho transformeru
        Transformer transformer = factory.newTransformer();
        // Vstupem transformace bude dokument v pameti
        DOMSource source = new DOMSource(doc);
        // Vystupem transformace bude vystupni soubor
        StreamResult result = new StreamResult(output.toString());
        // Provedeme transformaci
        transformer.transform(source, result);
    }
}